<template>
  <div class="app-container">
    <h2 class="title">发布新课程</h2>

    <el-steps
      :active="2"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>

    <el-button type="danger" class="add-button" @click="AdddialogFormVisible">
      添加章节
    </el-button>

    <el-dialog v-model="dialogFormVisible" :title="chapterTitle" width="500">
      <el-form :model="chapterFrom">
        <el-form-item label="章节标题" :label-width="formLabelWidth">
          <el-input v-model="chapterFrom.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="章节排序" :label-width="formLabelWidth">
          <el-input v-model="chapterFrom.sort" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateChatper">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <ul class="chapter-list">
      <li
        v-for="chapter in ChapterVideoList"
        :key="chapter.id"
        class="chapter-item"
      >
        <p>
          {{ chapter.title }}
          <span class="actions">
            <el-button type="text" @click="addVideo(chapter.id)"
              >添加课时</el-button
            >
            <el-button type="text" @click="editChapter(chapter.id)"
              >编辑</el-button
            >
            <el-button type="text" @click="delChapter(chapter.id)"
              >删除</el-button
            >
          </span>
        </p>

        <ul class="video-list">
          <li
            v-for="video in chapter.children"
            :key="video.id"
            class="video-item"
          >
            <p>
              {{ video.title }}
              <span class="actions">
                <el-button type="text" @click="editVideo(video.id)"
                  >编辑</el-button
                >
                <el-button type="text" @click="delVideo(video.id)"
                  >删除</el-button
                >
              </span>
            </p>
          </li>
        </ul>
      </li>
    </ul>

    <el-form label-width="120px" class="navigation-buttons">
      <el-form-item>
        <el-button type="primary" @click="previous">上一步</el-button>
        <el-button type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVideoFormVisible" :title="videoTitle">
      <el-form :model="video" label-width="120px">
        <el-form-item label="课时标题">
          <el-input v-model="video.title" />
        </el-form-item>
        <el-form-item label="课时排序">
          <el-input-number
            v-model="video.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio-group v-model="video.free">
            <el-radio :label="true">免费</el-radio>
            <el-radio :label="false">默认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            :on-success="handleVideoSuccess"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :action="uploadUrl + '/serviceedu/edu-video/upload'"
            :limit="1"
            class="upload-demo"
          >
            <el-button size="small" type="primary">上传视频</el-button>
            <div class="el-upload__tip">
                最大上传1G视频，上传格式为视频格式
              </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVideoFormVisible = false">取 消</el-button>
        <el-button
          :disabled="saveVideoBtnDisabled"
          type="primary"
          @click="saveOrUpdateVideo"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { number } from "echarts";
import axios from "../../assets/js/axios";
import {
  type Action,
  ElMessage,
  ElMessageBox,
  ElTree,
  UploadProps,
  UploadUserFile,
} from "element-plus";
import { ref, watch, reactive, type Ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ChatRound } from "@element-plus/icons-vue";
const uploadUrl = import.meta.env.VITE_URL;
const chapterTitle = ref("");
const videoTitle = ref("");
const active = ref(2);
const router = useRouter();
const route = useRoute();
const ChapterVideoList = ref<any>([]);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
interface Chapter {
  title: string;
  sort: number;
  id: number;
}
const chapterFrom = reactive<Chapter>({
  title: "",
  sort: 0,
  id: 0,
});
interface VideoType {
  title: string;
  sort: number;
  free: number;
  duration:number;
  videoSourceId: string;
  videoOriginalName: string;
  chapterId?: number;
  courseId?: number;
  id: number;
}

// 假设 video.value 是这个类型的实例
const video: Ref<VideoType> = ref({
  title: "",
  duration:0,
  sort: 0,
  free: 0,
  videoOriginalName: "",
  videoSourceId: "",
  id: 0,
});
const saveVideoBtnDisabled = ref(false); // 课时按钮是否禁用
const dialogVideoFormVisible = ref(false); // 是否显示课时表单
const next = () => {
  router.push("/publish/" + route.params.id);
  console.log("courseId:" + route.params.id);
};

const courseId = ref(route.params.id);
const courseIdStr = String(courseId.value);
//上传视频
const getChapterList = () => {
  //课程大纲列表
  axios
    .get(`/serviceedu/edu-chapter/getChapterList/${courseIdStr}`, {})
    .then((res: any) => {
      console.log(res);
      ChapterVideoList.value = res.data.list;
    })
    .catch((error) => {
      console.error("请求失败:", error);
    });
};
getChapterList();
//修改课程表单
const previous = () => {
  router.push({ path: "/info", query: { id: courseIdStr } });
};
//更改章节
//1 数据回显
const editChapter = (chapterId: number) => {
  chapterTitle.value = "编辑课程";
  dialogFormVisible.value = true;
  axios
    .get("/serviceedu/edu-chapter/getChapterInfo/" + chapterId, {})
    .then((res: any) => {
      chapterFrom.id = res.data.data.id;
      chapterFrom.title = res.data.data.title;
      chapterFrom.sort = res.data.data.sort;
      router.push({ query: { id: chapterFrom.id } });
    });
};
//修改标题按钮
const AdddialogFormVisible = () => {
  chapterTitle.value = "添加课程";
  dialogFormVisible.value = true;
};

//添加章节,修改章节
const addOrUpdateChatper = () => {
  // 根据 id 的存在与否来决定是更新还是添加章节
  if (chapterFrom.id) {
    // 更新章节
    axios
      .put("/serviceedu/edu-chapter/updateChapter", chapterFrom)
      .then((res: any) => {
        if (res.code === 200) {
          dialogFormVisible.value = false;
          ElMessage({
            type: "success",
            message: "修改章节成功",
          });
          // 重置表单
          chapterFrom.title = "";
          chapterFrom.sort = 0;
          getChapterList();
        }
      })
      .catch((error) => {
        console.error("更新章节失败:", error);
        ElMessage.error("更新章节失败");
      });
  } else {
    //添加章节
    const chapterData = {
      ...chapterFrom,
      courseId: courseId.value,
    };
    axios
      .post("/serviceedu/edu-chapter/addChapter", chapterData)
      .then((res: any) => {
        if (res.code === 200) {
          dialogFormVisible.value = false;
          ElMessage({
            type: "success",
            message: "保存章节成功",
          });
          getChapterList();
          // 注意：这里重置的应该是原始表单对象，而不是刚创建的 chapterData
          chapterFrom.title = "";
          chapterFrom.sort = 0;
        }
      })
      .catch((error) => {
        console.error("添加章节失败:", error);
        ElMessage.error("添加章节失败");
      });
  }
};

//删除章节
const delChapter = (chapterId: number) => {
  ElMessageBox.alert("确认删除吗？", "提示", {
    confirmButtonText: "确认",
    callback: (action: Action) => {
      console.log("Deleting chapter with ID:", chapterId); // 调试输出
      console.log(action);
      if (action === "confirm") {
        axios
          .del(`/serviceedu/edu-chapter/chapters/${chapterId}`, {})
          .then((res: any) => {
            if (res.code === 200) {
              //提示删除成功
              ElMessage({
                message: "删除数据成功",
                type: "success",
              });
              // 刷新列表
              getChapterList();
            }
          });
      }
    },
  });
};
// 添加课时
const addVideo = (chapterId: number) => {
  videoTitle.value = "添加小结";
  dialogVideoFormVisible.value = true;
  video.value.chapterId = chapterId;
  video.value.courseId = courseId;
};

//删除小结
const delVideo = (videoId: number) => {
  ElMessageBox.alert("确认删除吗？", "提示", {
    confirmButtonText: "确认",
    callback: (action: Action) => {
      console.log("Deleting chapter with ID:", videoId); // 调试输出
      console.log(action);
      if (action === "confirm") {
        axios
          .del(`/serviceedu/edu-video/deleteVideo/${videoId}`, {})
          .then((res: any) => {
            if (res.code === 200) {
              //提示删除成功
              ElMessage({
                message: "删除数据成功",
                type: "success",
              });
              // 刷新列表
              getChapterList();
            }
          });
      }
    },
  });
};
//添加小结标题
const newFileItem = {  
  name: video.value.videoOriginalName  
};  
//小结编辑
const editVideo = (videoId: number) => {
  videoTitle.value = "编辑小结";
  dialogVideoFormVisible.value = true;
  axios  
    .get("/serviceedu/edu-video/getVideo/" + videoId,{})  
    .then((res: any) => {  
      // 更新 video.value 的属性  
      video.value.id = res.data.data.id;  
      video.value.title = res.data.data.title;  
      video.value.sort = res.data.data.sort;  
      video.value.free = res.data.data.free;  
      video.value.duration = res.data.data.duration;  
      video.value.videoSourceId = res.data.data.videoSourceId;  
 
      // 如果服务器没有返回视频文件名，则不添加到 fileList  
      if (res.data.data.videoOriginalName) {  
        fileList.value = [{'name': res.data.data.videoOriginalName}];  
      } else {  
        fileList.value = []; // 或者保持为空，如果不需要显示任何文件  
      }  
    });  
};
// 保存或更新视频
const saveOrUpdateVideo = () => {
  if (video.value.id) {
    axios
      .put("/serviceedu/edu-video/updateVideo", video.value)
      .then((res: any) => {
        dialogVideoFormVisible.value = false;
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "更新小结成功",
          });
          // 重置视频表单
          video.value.title = "";
          video.value.free = 0;
          video.value.sort = 0;
          video.value.videoSourceId = "";
          video.value.duration = 0; // 重置视频时长
          getChapterList();
        }
      })
      .catch((error) => {
        console.error("添加课时失败:", error);
        ElMessage.error("添加课时失败");
      });
  } else {
    axios
      .post("/serviceedu/edu-video/addVideo", video.value)
      .then((res: any) => {
        dialogVideoFormVisible.value = false;
        if (res.code === 200) {
          ElMessage({
            type: "success",
            message: "添加小结成功",
          });
        
          // 重置视频表单
          video.value.title = "";
          video.value.free = 0;
          video.value.sort = 0;
          video.value.videoSourceId = "";
          video.value.duration = 0; // 重置视频时长
          getChapterList();
        }
      })
      .catch((error) => {
        console.error("添加课时失败:", error);
        ElMessage.error("添加课时失败");
      });
  }
};

//视频相关的方法
// 处理上传成功
let fileList = ref<UploadUserFile[]>([]);
// 文件删除时

// 超出限制
const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning("最多上传一个视频");
};
// 视频文件上传成功
const handleVideoSuccess: UploadProps["onSuccess"] = (response, file, fileList) => {
  console.log(response); // 打印服务器返回的响应
  if (response && response.data && response.data.data.videoId) {
    video.value.videoSourceId = response.data.data.videoId;
    video.value.videoOriginalName = file.name; 
    video.value.duration = response.data.data.duration; // 保存视频时长
    ElMessage({
      message: "视频上传成功",
      type: "success",
    });
  } else {
    ElMessage.error("视频上传失败，请重试");
  }
};
const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return confirm(`确定删除 ${uploadFile.name}？`);
  
};
const handleRemove: UploadProps["onRemove"] = (file, fileListAsArray) => {  
  console.log(file, fileListAsArray); // 注意：fileListAsArray 可能是当前文件列表的数组形式  
  console.log(video.value.videoSourceId);  
  
  if (!video.value.videoSourceId) {  
    ElMessage.error("没有上传的视频可以删除");  
    return;  
  }  
  
  axios  
    .del(`/serviceedu/edu-video/removeVideo/${video.value.videoSourceId}`,{})  
    .then(() => {  
      // 清空相关状态  
      video.value.videoSourceId = ''; // 或者使用 ''，但 null 可能更清晰表示“无”  
      video.value.videoOriginalName = '';  
      fileList.value = []; // 确保文件列表被清空  
      ElMessage({  
        message: "删除数据成功",  
        type: "success",  
      });  
    })  
    .catch((error) => {  
      console.error("删除视频时发生错误:", error);  
      ElMessage.error("删除视频时发生错误，请重试");  
    });  
};  
//上传视频前提示

</script>
<style lang="less" scoped>
.app-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.title {
  text-align: center;
  color: #333;
  font-family: "Avenir", "Helvetica Neue", "Arial", sans-serif;
}

.add-button {
  margin-bottom: 20px;
  background-color: #ff4d4f;
  color: white;
}

.chapter-list {
  list-style: none;
  padding: 0;
}

.chapter-item {
  margin-bottom: 15px;
  padding: 10px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.chapter-item:hover {
  background-color: #f5f5f5;
}

.actions {
  float: right;
}

.video-list {
  padding-left: 30px;
}

.video-item {
  margin-top: 8px;
  padding: 8px;
  background-color: #f9f9f9;
  border: 1px dashed #ddd;
}

.video-item:hover {
  background-color: #f0f0f0;
}

.navigation-buttons {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>